package apiFun

import (
	"cake-server/module"
	"cake-server/utils"
	"net/http"

	"fmt"

	"github.com/gin-gonic/gin"
)

type RoleSearch struct {
	module.Roles
	Limit
}

func GetRoles(c *gin.Context) {
	var roles []module.Roles
	var searchInfo RoleSearch
	var toatalCount int64
	err := c.ShouldBindQuery(&searchInfo)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "参数错误",
			"error":   err.Error(),
		})
		return
	}
	if searchInfo.IsPage {
		module.DB.Model(&module.Roles{}).Where("name like ?", utils.VagueFormat(searchInfo.Name)).Count(&toatalCount)
		result := module.DB.Where("name like ?", utils.VagueFormat(searchInfo.Name)).Limit(searchInfo.PageSize).Offset((searchInfo.PageIndex - 1) * searchInfo.PageSize).Find(&roles)
		if result.RowsAffected > 0 {
			c.JSON(http.StatusOK, gin.H{
				"code":       200,
				"message":    "获取成功",
				"data":       roles,
				"totalCount": toatalCount,
			})
		} else {
			c.JSON(http.StatusOK, gin.H{
				"code":       400,
				"message":    "无数据",
				"data":       roles,
				"totalCount": 0,
			})
		}
	} else {
		var roles []module.Roles
		result := module.DB.Find(&roles)
		if result.RowsAffected > 0 {
			c.JSON(http.StatusOK, gin.H{
				"code":    200,
				"message": "查询成功",
				"data":    roles,
			})
		} else {
			c.JSON(http.StatusOK, gin.H{
				"code":       400,
				"message":    "无数据",
				"data":       roles,
				"totalCount": 0,
			})
		}
	}
}

func AddRoles(c *gin.Context) {
	var role module.Roles
	err := c.ShouldBind(&role)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "参数错误",
			"error":   err.Error(),
		})
		return
	}
	result := module.DB.Where("name = ?", role.Name).First(&role)
	if result.RowsAffected > 0 {
		c.JSON(http.StatusOK, gin.H{
			"code":    400,
			"message": "角色已存在",
		})
		return
	}
	result = module.DB.Create(&role)
	if result.RowsAffected > 0 {
		c.JSON(http.StatusOK, gin.H{
			"code":    200,
			"message": "添加成功",
			"data":    role,
		})
	} else {
		c.JSON(http.StatusOK, gin.H{
			"code":    400,
			"message": "添加失败",
			"err":     result.Error,
		})
	}
}
func UpdateRoles(c *gin.Context) {
	var role module.Roles
	err := c.ShouldBind(&role)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "参数错误",
		})
		return
	}
	result := module.DB.Model(&role).Updates(role)
	if result.RowsAffected > 0 {
		c.JSON(http.StatusOK, gin.H{
			"code":    200,
			"message": "更新成功",
		})
	} else {
		c.JSON(http.StatusOK, gin.H{
			"code":    400,
			"message": "更新失败",
			"err":     result.Error,
		})
	}
}
func DeleteRoles(c *gin.Context) {
	var roleIds []int
	err := c.ShouldBind(&roleIds)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "参数错误",
			"error":   err.Error(),
		})
		return
	}
	result := module.DB.Where("id IN (?)", roleIds).Delete(&module.Roles{})
	if result.RowsAffected > 0 {
		c.JSON(http.StatusOK, gin.H{
			"code":    200,
			"message": "删除成功",
		})
	} else {
		c.JSON(http.StatusOK, gin.H{
			"code":    400,
			"message": "删除失败",
			"err":     result.Error,
		})
	}
}

type Menus struct {
	Id          int      `json:"id"`
	Permissions []string `json:"permissions"`
}
type BindParameter struct {
	RoleId int     `json:"roleId"`
	Menus  []Menus `json:"menus"`
}

// BindMenu 绑定菜单到角色
func BindMenu(c *gin.Context) {
	var role_menus []module.Role_Menus
	var bindParameter BindParameter
	err := c.ShouldBind(&bindParameter)
	fmt.Println(bindParameter)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "参数错误",
			"error":   err.Error(),
		})
		return
	}
	tx := module.DB.Begin()
	//清除所有绑定的菜单
	result := tx.Where("role_id = ?", bindParameter.RoleId).Delete(&module.Role_Menus{})
	if result.Error != nil {
		tx.Rollback()
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "清除绑定的菜单失败",
			"error":   result.Error,
		})
		return
	}
	//整理格式
	for _, value := range bindParameter.Menus {
		role_menus = append(role_menus, module.Role_Menus{
			Role_Id: bindParameter.RoleId,
			Menu_Id: value.Id,
		})
	}
	fmt.Println(role_menus)
	//批量插入绑定的菜单
	result = tx.Create(&role_menus)
	if result.Error != nil {
		// 处理错误
		tx.Rollback()
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "绑定失败",
			"error":   result.Error,
		})
	}
	if result.RowsAffected > 0 {
		c.JSON(http.StatusOK, gin.H{
			"code":    200,
			"message": "绑定成功",
		})
		//成功完成后提交事务
		tx.Commit()
	} else {
		//发生错误时候回滚
		tx.Rollback()
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "绑定失败",
			"error":   result.Error,
		})
	}
}

// 查询角色菜单权限
func GetRoleMenuIds(c *gin.Context) {
	var roleMenus []module.Role_Menus
	var menusIds []int
	roleId := c.Query("roleId")

	if len(roleId) > 0 {
		result := module.DB.Where("role_id = ?", roleId).Find(&roleMenus)
		if result.RowsAffected > 0 {
			for _, value := range roleMenus {
				menusIds = append(menusIds, value.Menu_Id)
			}
			c.JSON(http.StatusOK, gin.H{
				"code":    200,
				"message": "查询成功",
				"data":    menusIds,
			})
		} else {
			c.JSON(http.StatusOK, gin.H{
				"code":    400,
				"message": "查询失败",
				"error":   menusIds,
			})
		}
	} else {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "参数错误",
			"error":   "roleId不能为空",
		})
	}
}

func GetRoleMenus(c *gin.Context) {

}
